package com.bw.service;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.bw.entity.AssetInfo;
import com.bw.entity.Dict;
import com.bw.mapper.AssetsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.Valid;
import java.util.List;

@Service
public class AssetsServiceImpl implements AssetsService {

    @Autowired
    AssetsMapper assetsMapper;


    @Override
    public AssetInfo selectByNum(String num) {

        AssetInfo info = assetsMapper.selectByNum(num);

        List<Dict> typeList = assetsMapper.selectType();
        info.setTypeList(typeList);

        List<Dict> sourceList = assetsMapper.selectSource();
        info.setSourceList(sourceList);

        return info;
    }

    @Override
    public AssetInfo addAssets(AssetInfo assetInfo) {

//        表单非空校验，“*”非空字段

        if (assetInfo.getTypeId() == null) {
            throw new RuntimeException("资产类型不为空");
        }
        if (StrUtil.isBlank(assetInfo.getName())) {
            throw new RuntimeException("资产名称不为空");
        }
        if (StrUtil.isBlank(assetInfo.getCreateTime())) {
            throw new RuntimeException("日期不为空");
        }

        //断言  断定 判定  notNull 判断 非 string类型
        Assert.notNull(assetInfo.getSourceId(), "资产来源不为空"); // 代替下面注释的代码
//        if (assetInfo.getSourceId() == null) {
//            throw new RuntimeException("资产来源不为空");
//        }

        //断言  断定 判定  notBlank 判断string类型
        Assert.notBlank(assetInfo.getPrice(), "价格不为空");  // 代替下面注释的代码
//        if (StrUtil.isBlank(assetInfo.getPrice())) {
//            throw new RuntimeException("价格不为空");
//        }

//        资产编号唯一性校验(资产编号不能重复)
        AssetInfo assetInfoDB = assetsMapper.selectByNum(assetInfo.getNum());
        if (assetInfoDB != null) {
            throw new RuntimeException("资产编号重复");
        }



//        购入价格校验，必须为数值类型

        String price = assetInfo.getPrice();

        boolean number = NumberUtil.isNumber(price);
        if (!number){
            throw new RuntimeException("价格必须是数字");
        }


//        控制打印方法参数
        System.out.println(assetInfo);


//        (14)添加成功，   返回资产对象
        assetsMapper.add(assetInfo);

        return assetInfo;
    }
}
